﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using log4net;
using CashFlow.Db.Entity;
using CashFlow.Db.DAL;
using ConsoleApplication1._00_Def;
using ConsoleApplication1._01_Config;
using ConsoleApplication1._02_Common;
using ConsoleApplication1._03_Service;
using ConsoleApplication1._03_Service._00_Db;

namespace ConsoleApplication1._03_Service._01_Jobs
{
    public class AccountingService
    {
        private static ILog _logger = LogManager.GetLogger(typeof(AccountingService));

        public static void Calc()
        {
            try
            {
                string date = MyCommonTool.GetOrderDate();
                var orders = OrderService.QueryAll(date);
                if (orders.Count == 0)
                {
                    _logger.Info("未查询到任何订单信息, Date: " + date);
                    return;
                }

                var users = UserService.QueryAll();
                var shops = ShopService.QueryAll();
                var shopUsers = ShopUserService.QueryAll();
                var ls = new List<FeeEntity>();

                _logger.Info("开始计算服务费用, Date: " + date);
                #region 计算各种服务费用
                foreach (var item in users)
                {
                    var feeItemData = new FeeEntity();
                    feeItemData.UserId = item.Id;
                    feeItemData.Date = date;
                    ls.Add(feeItemData);

                    var childUserIds = UserRelationShipTool.GetShopAllChildUserIds(item, users, shopUsers);
                    var orders2 = orders.Where(x => childUserIds.Contains(x.BuyerUserId)).ToList();
                    decimal percent = 0M;
                    if (item.ShopManagerLevelPercent == 0)
                    {
                        percent = ShopManagerLevelTool.GetShopManagerLevelPercent(orders2.Count);
                    }
                    else
                    {
                        percent = item.ShopManagerLevelPercent;
                    }

                    #region 计算订单利润
                    {
                        var order = orders.Where(x => x.BuyerUserId == item.Id).FirstOrDefault();
                        if (order != null && order.Id > 0)
                        {
                            feeItemData.OrderProfitFee = order.Amount * Consts.OrderPrefitPercent;
                        }
                    }
                    #endregion

                    #region 计算店长管理费
                    {
                        decimal sum = 0M;
                        var ls2 = users.Where(x => x.ReferenceInvitationCode == item.InvitationCode).ToList();
                        foreach (var item2 in ls2)
                        {
                            var childUserIds2 = UserRelationShipTool.GetShopAllChildUserIds(item2, users, shopUsers);
                            var orders3 = orders.Where(x => childUserIds2.Contains(x.BuyerUserId)).ToList();
                            decimal percent2 = 0M;
                            if (item2.ShopManagerLevelPercent == 0)
                            {
                                percent2 = ShopManagerLevelTool.GetShopManagerLevelPercent(orders3.Count);
                            }
                            else
                            {
                                percent2 = item2.ShopManagerLevelPercent;
                            }
                            if (percent > percent2)
                            {
                                var sum2 = orders3.Sum(x => x.Amount) * (percent - percent2);
                                sum += sum2;
                            }
                        }
                        feeItemData.ShopManagerManageFee = sum;
                    }
                    #endregion

                    #region 计算分红
                    {
                        int n = shops.Where(x => x.ShopManagerUserId == item.Id).Count();
                        if (n > 0)
                        {
                            var sum = orders2.Sum(x => x.Amount);
                            feeItemData.BoundFee = sum * Consts.BonusPercent;
                        }
                    }
                    #endregion

                    #region 计算寄售服务费
                    {
                        var sum = orders2.Sum(x => x.Amount);
                        var percent2 = Consts.ShopManagerMaxPercent + Consts.ConsignSalePercent - percent;
                        feeItemData.ConsignmentSaleFee = percent2 * sum;
                    }
                    #endregion
                }
                #endregion

                #region 更新到数据库
                using (var db = SqlSugarHelper.GetDb())
                {
                    try
                    {
                        db.BeginTran();

                        db.Deleteable<FeeEntity>(x => x.Date == date).ExecuteCommand();
                        db.Insertable<FeeEntity>(ls).ExecuteCommand();

                        _logger.Info("准备更新到数据库");
                        db.CommitTran();
                        _logger.Info("更新数据库成功！");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error(ex);
                        db.RollbackTran();
                    }
                }
                #endregion

                users.Clear();
                orders.Clear();
                shops.Clear();
                shopUsers.Clear();

                _logger.Info(string.Format("计算费用完毕, 日期: {0}", date));
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex);
            }
        }
    }
}
